/**
 * 处理副作用
 */
export type EffectCleaner = () => any
export type EffectHook = (() => EffectCleaner) | (() => void)
export function useEffects(hooks: EffectHook | EffectHook[], cleaners?: EffectCleaner[]) {
  // 清除模块副作用
  if (Array.isArray(cleaners)) {
    cleanEffects(cleaners)
    onBeforeUnmount(() => cleanEffects(cleaners))
  }

  // 执行模块初始化
  if (!Array.isArray(hooks)) {
    hooks = [hooks]
  }
  hooks.forEach((hook) => {
    try {
      const cleaner = hook()
      if (typeof cleaner === 'function' && Array.isArray(cleaners)) {
        cleaners.push(cleaner)
      }
    } catch (e) {
      console.error('Fatal: Unable to call effect function.')
    }
  })
}
// 清除模块副作用
export function cleanEffects(cleaners: EffectCleaner[]) {
  cleaners.forEach((cleaner) => {
    try {
      cleaner()
    } catch (e) {
      console.error('Fatal: Unable to call cleaner function.')
    }
  })
  cleaners.splice(0)
}
